// 代码格式化工具渲染器
window.CodeFormatterRenderer = class CodeFormatterRenderer {
    static getHTML() {
        return `
            <h2 class="text-3xl font-bold text-gray-800 mb-6">
                <i data-feather="code" class="w-8 h-8 inline mr-3 text-blue-600"></i>
                代码格式化工具
            </h2>
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
                <p class="text-gray-600">支持多种编程语言的代码格式化、美化和压缩，提升代码可读性。</p>
            </div>
            
            <!-- 工具栏 -->
            <div class="bg-white rounded-xl shadow-sm border p-4 mb-6">
                <div class="flex flex-wrap gap-3 mb-4">
                    <!-- 语言选择 -->
                    <select 
                        id="language-select" 
                        class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                        <option value="javascript">JavaScript</option>
                        <option value="typescript">TypeScript</option>
                        <option value="python">Python</option>
                        <option value="java">Java</option>
                        <option value="csharp">C#</option>
                        <option value="cpp">C++</option>
                        <option value="c">C</option>
                        <option value="go">Go</option>
                        <option value="rust">Rust</option>
                        <option value="php">PHP</option>
                        <option value="ruby">Ruby</option>
                        <option value="swift">Swift</option>
                        <option value="kotlin">Kotlin</option>
                        <option value="html">HTML</option>
                        <option value="css">CSS</option>
                        <option value="scss">SCSS</option>
                        <option value="json">JSON</option>
                        <option value="xml">XML</option>
                        <option value="yaml">YAML</option>
                        <option value="sql">SQL</option>
                    </select>
                    
                    <!-- 操作按钮 -->
                    <button 
                        id="format-code" 
                        class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="align-left" class="w-4 h-4 mr-2"></i>
                        格式化
                    </button>
                    <button 
                        id="minify-code" 
                        class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="minimize-2" class="w-4 h-4 mr-2"></i>
                        压缩
                    </button>
                    <button 
                        id="detect-language" 
                        class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="search" class="w-4 h-4 mr-2"></i>
                        检测语言
                    </button>
                    
                    <!-- 文件操作 -->
                    <label class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center cursor-pointer">
                        <i data-feather="upload" class="w-4 h-4 mr-2"></i>
                        加载文件
                        <input type="file" id="file-input" class="hidden" accept=".js,.ts,.py,.java,.cs,.cpp,.c,.h,.go,.rs,.php,.rb,.swift,.kt,.html,.css,.scss,.json,.xml,.yml,.yaml,.sql">
                    </label>
                    <button 
                        id="download-code" 
                        class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="download" class="w-4 h-4 mr-2"></i>
                        下载
                    </button>
                    <button 
                        id="copy-result" 
                        class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                        复制结果
                    </button>
                    <button 
                        id="clear-code" 
                        class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                        清空
                    </button>
                </div>

                <!-- 格式化选项 -->
                <div class="border-t pt-4">
                    <h4 class="text-sm font-medium text-gray-700 mb-3">格式化选项</h4>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div class="flex items-center">
                            <label class="flex items-center text-sm text-gray-600">
                                <input type="radio" name="indent-type" value="space" checked class="mr-2">
                                空格缩进
                            </label>
                        </div>
                        <div class="flex items-center">
                            <label class="flex items-center text-sm text-gray-600">
                                <input type="radio" name="indent-type" value="tab" class="mr-2">
                                Tab缩进
                            </label>
                        </div>
                        <div class="flex items-center">
                            <label class="text-sm text-gray-600 mr-2">缩进大小:</label>
                            <select id="indent-size" class="px-2 py-1 border border-gray-300 rounded text-sm">
                                <option value="2" selected>2</option>
                                <option value="4">4</option>
                                <option value="8">8</option>
                            </select>
                        </div>
                        <div class="flex items-center">
                            <label class="flex items-center text-sm text-gray-600">
                                <input type="checkbox" id="insert-final-newline" checked class="mr-2">
                                末尾添加换行
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 代码编辑区域 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <!-- 输入区域 -->
                <div class="bg-white rounded-xl shadow-sm border">
                    <div class="flex items-center justify-between p-4 border-b">
                        <h3 class="text-lg font-semibold text-gray-700">原始代码</h3>
                        <div class="text-sm text-gray-500">
                            <span id="input-stats">行数: 0 | 大小: 0 B</span>
                        </div>
                    </div>
                    <div class="relative">
                        <textarea 
                            id="code-input" 
                            class="w-full h-96 p-4 font-mono text-sm border-none resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 rounded-b-xl"
                            placeholder="在此粘贴或输入代码，支持拖拽文件上传..."
                            spellcheck="false"
                        ></textarea>
                        <!-- 拖拽上传提示 -->
                        <div id="drop-zone" class="absolute inset-0 bg-blue-50 border-2 border-dashed border-blue-300 rounded-b-xl flex items-center justify-center hidden">
                            <div class="text-center">
                                <i data-feather="upload-cloud" class="w-12 h-12 text-blue-400 mx-auto mb-2"></i>
                                <p class="text-blue-600 font-medium">拖拽代码文件到此处</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 输出区域 -->
                <div class="bg-white rounded-xl shadow-sm border">
                    <div class="flex items-center justify-between p-4 border-b">
                        <h3 class="text-lg font-semibold text-gray-700">格式化结果</h3>
                        <div class="text-sm text-gray-500">
                            <span id="output-stats">行数: 0 | 大小: 0 B</span>
                        </div>
                    </div>
                    <div class="relative">
                        <pre id="code-output" class="w-full h-96 p-4 font-mono text-sm bg-gray-50 overflow-auto whitespace-pre-wrap rounded-b-xl"></pre>
                    </div>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="bg-white rounded-xl shadow-sm border p-6">
                <h3 class="text-lg font-semibold text-gray-700 mb-4">处理统计</h3>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div class="text-center p-3 bg-blue-50 rounded-lg">
                        <div class="text-2xl font-bold text-blue-600" id="stat-original-lines">0</div>
                        <div class="text-sm text-gray-600">原始行数</div>
                    </div>
                    <div class="text-center p-3 bg-green-50 rounded-lg">
                        <div class="text-2xl font-bold text-green-600" id="stat-formatted-lines">0</div>
                        <div class="text-sm text-gray-600">格式化行数</div>
                    </div>
                    <div class="text-center p-3 bg-orange-50 rounded-lg">
                        <div class="text-2xl font-bold text-orange-600" id="stat-original-size">0 B</div>
                        <div class="text-sm text-gray-600">原始大小</div>
                    </div>
                    <div class="text-center p-3 bg-purple-50 rounded-lg">
                        <div class="text-2xl font-bold text-purple-600" id="stat-formatted-size">0 B</div>
                        <div class="text-sm text-gray-600">处理后大小</div>
                    </div>
                </div>
            </div>

            <style>
                /* 代码语法高亮样式 */
                .code-highlight {
                    background: #f8f9fa;
                    border: 1px solid #e9ecef;
                    border-radius: 6px;
                }

                /* JavaScript/TypeScript */
                .lang-javascript, .lang-typescript {
                    background: linear-gradient(135deg, #fff7ed 0%, #fef3c7 100%);
                }

                /* Python */
                .lang-python {
                    background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
                }

                /* Java/C# */
                .lang-java, .lang-csharp {
                    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
                }

                /* C/C++ */
                .lang-c, .lang-cpp {
                    background: linear-gradient(135deg, #f3e8ff 0%, #e9d5ff 100%);
                }

                /* Go */
                .lang-go {
                    background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
                }

                /* HTML/CSS */
                .lang-html, .lang-css {
                    background: linear-gradient(135deg, #fef7ff 0%, #fae8ff 100%);
                }

                /* JSON/XML */
                .lang-json, .lang-xml {
                    background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
                }

                /* SQL */
                .lang-sql {
                    background: linear-gradient(135deg, #f0f9ff 0%, #dbeafe 100%);
                }

                /* 拖拽区域动画 */
                .drag-over {
                    animation: pulse 1s infinite;
                    border-color: #3b82f6 !important;
                    background-color: #eff6ff !important;
                }

                @keyframes pulse {
                    0%, 100% { opacity: 1; }
                    50% { opacity: 0.8; }
                }

                /* 代码编辑器样式 */
                #code-input, #code-output {
                    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
                    line-height: 1.5;
                    tab-size: 4;
                }

                #code-output.formatted {
                    background: #f8f9fa;
                    border-left: 4px solid #28a745;
                }

                #code-output.minified {
                    background: #fff3cd;
                    border-left: 4px solid #ffc107;
                }

                /* 错误状态 */
                .error-state {
                    border-color: #dc3545 !important;
                    background-color: #f8d7da !important;
                }

                /* 成功状态 */
                .success-state {
                    border-color: #28a745 !important;
                    background-color: #d1ecf1 !important;
                }
            </style>
        `;
    }
    
    static init() {
        const codeInput = document.getElementById('code-input');
        const codeOutput = document.getElementById('code-output');
        const languageSelect = document.getElementById('language-select');
        const formatBtn = document.getElementById('format-code');
        const minifyBtn = document.getElementById('minify-code');
        const detectBtn = document.getElementById('detect-language');
        const fileInput = document.getElementById('file-input');
        const downloadBtn = document.getElementById('download-code');
        const copyBtn = document.getElementById('copy-result');
        const clearBtn = document.getElementById('clear-code');
        const dropZone = document.getElementById('drop-zone');
        
        // 格式化选项
        const indentSizeSelect = document.getElementById('indent-size');
        const insertFinalNewlineCheck = document.getElementById('insert-final-newline');
        
        // 统计显示元素
        const inputStats = document.getElementById('input-stats');
        const outputStats = document.getElementById('output-stats');
        
        let currentResult = null;

        // 初始化示例代码
        const initExample = () => {
            codeInput.value = `// JavaScript 示例代码
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

const numbers = [1,2,3,4,5];
const doubled = numbers.map(x=>x*2);
console.log(doubled);

class Calculator {
constructor(initial = 0) {
this.value = initial;
}
add(num) {
this.value += num;
return this;
}
}`;
            updateInputStats();
        };

        // 更新输入统计
        const updateInputStats = () => {
            const text = codeInput.value;
            const lines = text.split('\n').length;
            const size = new Blob([text]).size;
            inputStats.textContent = `行数: ${lines} | 大小: ${DevToolsUtils.formatFileSize(size)}`;
        };

        // 更新输出统计  
        const updateOutputStats = (result) => {
            if (result && result.data) {
                const stats = result.data.stats;
                outputStats.textContent = `行数: ${stats.formattedLines || stats.originalLines || 0} | 大小: ${DevToolsUtils.formatFileSize((stats.formattedSize || stats.minifiedSize || 0))}`;
                
                // 更新统计面板
                document.getElementById('stat-original-lines').textContent = stats.originalLines || 0;
                document.getElementById('stat-formatted-lines').textContent = stats.formattedLines || stats.originalLines || 0;
                document.getElementById('stat-original-size').textContent = DevToolsUtils.formatFileSize(stats.originalSize || 0);
                document.getElementById('stat-formatted-size').textContent = DevToolsUtils.formatFileSize(stats.formattedSize || stats.minifiedSize || 0);
            }
        };

        // 获取格式化选项
        const getFormatOptions = () => {
            const indentType = document.querySelector('input[name="indent-type"]:checked').value;
            return {
                indentSize: parseInt(indentSizeSelect.value),
                indentType: indentType,
                insertFinalNewline: insertFinalNewlineCheck.checked,
                trimTrailingWhitespace: true
            };
        };

        // 设置输出样式
        const setOutputStyle = (type) => {
            codeOutput.className = 'w-full h-96 p-4 font-mono text-sm bg-gray-50 overflow-auto whitespace-pre-wrap rounded-b-xl';
            if (type === 'formatted') {
                codeOutput.classList.add('formatted');
            } else if (type === 'minified') {
                codeOutput.classList.add('minified');
            }
        };

        // 格式化代码
        formatBtn.addEventListener('click', () => {
            const code = codeInput.value.trim();
            if (!code) {
                DevToolsUtils.showToast('请输入代码', 'warning');
                return;
            }

            DevToolsUtils.addLoading(formatBtn);
            
            try {
                const language = languageSelect.value;
                const options = getFormatOptions();
                const result = CodeFormatter.formatCode(code, language, options);
                
                if (result.success) {
                    currentResult = result;
                    codeOutput.textContent = result.data.formatted;
                    setOutputStyle('formatted');
                    updateOutputStats(result);
                    
                    // 添加语言样式类
                    codeOutput.classList.add(`lang-${language}`);
                    
                    DevToolsUtils.showToast('代码格式化成功', 'success');
                } else {
                    codeOutput.textContent = result.error;
                    codeOutput.classList.add('error-state');
                    DevToolsUtils.showToast(result.error, 'error');
                }
            } catch (error) {
                codeOutput.textContent = `格式化错误: ${error.message}`;
                codeOutput.classList.add('error-state');
                DevToolsUtils.showToast('格式化失败', 'error');
            }
            
            DevToolsUtils.removeLoading(formatBtn);
        });

        // 压缩代码
        minifyBtn.addEventListener('click', () => {
            const code = codeInput.value.trim();
            if (!code) {
                DevToolsUtils.showToast('请输入代码', 'warning');
                return;
            }

            DevToolsUtils.addLoading(minifyBtn);
            
            try {
                const language = languageSelect.value;
                const result = CodeFormatter.minifyCode(code, language);
                
                if (result.success) {
                    currentResult = result;
                    codeOutput.textContent = result.data.minified;
                    setOutputStyle('minified');
                    updateOutputStats(result);
                    
                    const compressionRatio = result.data.stats.compressionRatio;
                    DevToolsUtils.showToast(`代码压缩成功，压缩率: ${compressionRatio}%`, 'success');
                } else {
                    codeOutput.textContent = result.error;
                    codeOutput.classList.add('error-state');
                    DevToolsUtils.showToast(result.error, 'error');
                }
            } catch (error) {
                codeOutput.textContent = `压缩错误: ${error.message}`;
                codeOutput.classList.add('error-state');
                DevToolsUtils.showToast('压缩失败', 'error');
            }
            
            DevToolsUtils.removeLoading(minifyBtn);
        });

        // 检测语言
        detectBtn.addEventListener('click', () => {
            const code = codeInput.value.trim();
            if (!code) {
                DevToolsUtils.showToast('请输入代码', 'warning');
                return;
            }

            try {
                const detectedLanguage = CodeFormatter.detectLanguage(code);
                languageSelect.value = detectedLanguage;
                DevToolsUtils.showToast(`检测到语言: ${CodeFormatter.languages[detectedLanguage].name}`, 'success');
            } catch (error) {
                DevToolsUtils.showToast('语言检测失败', 'error');
            }
        });

        // 文件上传处理
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            // 检测语言
            const detectedLanguage = CodeFormatter.detectLanguage('', file.name);
            languageSelect.value = detectedLanguage;

            const reader = new FileReader();
            reader.onload = (e) => {
                codeInput.value = e.target.result;
                updateInputStats();
                DevToolsUtils.showToast(`文件加载成功: ${file.name}`, 'success');
            };
            reader.onerror = () => {
                DevToolsUtils.showToast('文件读取失败', 'error');
            };
            reader.readAsText(file);
        });

        // 拖拽上传
        codeInput.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.remove('hidden');
            dropZone.classList.add('drag-over');
        });

        codeInput.addEventListener('dragleave', (e) => {
            if (!codeInput.contains(e.relatedTarget)) {
                dropZone.classList.add('hidden');
                dropZone.classList.remove('drag-over');
            }
        });

        codeInput.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.add('hidden');
            dropZone.classList.remove('drag-over');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                const file = files[0];
                
                // 检测语言
                const detectedLanguage = CodeFormatter.detectLanguage('', file.name);
                languageSelect.value = detectedLanguage;

                const reader = new FileReader();
                reader.onload = (e) => {
                    codeInput.value = e.target.result;
                    updateInputStats();
                    DevToolsUtils.showToast(`文件加载成功: ${file.name}`, 'success');
                };
                reader.readAsText(file);
            }
        });

        // 下载结果
        downloadBtn.addEventListener('click', () => {
            if (!currentResult) {
                DevToolsUtils.showToast('没有可下载的内容', 'warning');
                return;
            }

            try {
                const content = currentResult.data.formatted || currentResult.data.minified;
                const language = languageSelect.value;
                const extension = CodeFormatter.languages[language].extensions[0];
                const filename = `formatted_code.${extension}`;

                const blob = new Blob([content], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                a.click();
                URL.revokeObjectURL(url);
                
                DevToolsUtils.showToast('文件下载成功', 'success');
            } catch (error) {
                DevToolsUtils.showToast('下载失败', 'error');
            }
        });

        // 复制结果
        copyBtn.addEventListener('click', async () => {
            const output = codeOutput.textContent;
            if (!output) {
                DevToolsUtils.showToast('没有可复制的内容', 'warning');
                return;
            }

            const success = await DevToolsUtils.copyToClipboard(output);
            if (success) {
                DevToolsUtils.showToast('已复制到剪贴板', 'success');
            }
        });

        // 清空内容
        clearBtn.addEventListener('click', () => {
            codeInput.value = '';
            codeOutput.textContent = '';
            currentResult = null;
            updateInputStats();
            outputStats.textContent = '行数: 0 | 大小: 0 B';
            
            // 重置统计面板
            document.getElementById('stat-original-lines').textContent = '0';
            document.getElementById('stat-formatted-lines').textContent = '0';
            document.getElementById('stat-original-size').textContent = '0 B';
            document.getElementById('stat-formatted-size').textContent = '0 B';
            
            DevToolsUtils.showToast('内容已清空', 'info');
        });

        // 输入变化监听
        let inputTimeout;
        codeInput.addEventListener('input', () => {
            clearTimeout(inputTimeout);
            inputTimeout = setTimeout(updateInputStats, 300);
        });

        // 语言变化监听
        languageSelect.addEventListener('change', () => {
            const language = languageSelect.value;
            const config = CodeFormatter.languages[language];
            
            // 更新默认缩进设置
            indentSizeSelect.value = config.indent;
            const indentType = language === 'go' ? 'tab' : 'space';
            document.querySelector(`input[name="indent-type"][value="${indentType}"]`).checked = true;
        });

        // 初始化
        initExample();
        
        // 图标初始化
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};